package com.esm.sm800.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.esm.sm800.R;
import com.esm.sm800.database.dbmodel.Draw_report;
import com.esm.sm800.database.dbmodel.Needle;
import com.esm.sm800.database.manager.DrawreportCenter;
import com.esm.sm800.database.manager.MemberCenter;
import com.esm.sm800.database.manager.NeedleCenter;
import com.esm.sm800.database.manager.SystemCenter;
import com.esm.sm800.util.JtComm;
import com.esm.sm800.util.Utils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import zuo.biao.library.base.BaseActivity;
import zuo.biao.library.manager.TimeRefresher;

public class MainActivity extends BaseActivity implements View.OnClickListener, TimeRefresher.OnTimeRefreshListener {

    private final String TAG = "MainActivity";

    public static Intent createIntent(Context context) {
        return new Intent(context, MainActivity.class);
    }

    private final int[] CTR_IDS = {
            R.id.ctr_1, R.id.ctr_2, R.id.ctr_3, R.id.ctr_4,
            R.id.ctr_5, R.id.ctr_6, R.id.ctr_7, R.id.ctr_8,
            R.id.ctr_9, R.id.ctr_10, R.id.ctr_11, R.id.ctr_12,
    };
    //仓位背景
    private final int[] CBK_IDS = {
            R.id.ctlbk_1, R.id.ctlbk_2, R.id.ctlbk_3, R.id.ctlbk_4,
            R.id.ctlbk_5, R.id.ctlbk_6, R.id.ctlbk_7, R.id.ctlbk_8,
            R.id.ctlbk_9, R.id.ctlbk_10, R.id.ctlbk_11, R.id.ctlbk_12,
    };

    //仓位图片
    private final int[] STOCK_IDS = {
            R.id.stock_1, R.id.stock_2, R.id.stock_3, R.id.stock_4,
            R.id.stock_5, R.id.stock_6, R.id.stock_7, R.id.stock_8,
            R.id.stock_9, R.id.stock_10, R.id.stock_11, R.id.stock_12,
    };

    //仓位-针型号
    private final int[] ZXH_IDS = {
            R.id.tv_xh1, R.id.tv_xh2, R.id.tv_xh3, R.id.tv_xh4,
            R.id.tv_xh5, R.id.tv_xh6, R.id.tv_xh7, R.id.tv_xh8,
            R.id.tv_xh9, R.id.tv_xh10, R.id.tv_xh11, R.id.tv_xh12,
    };

    //仓位-针存量
    private final int[] CL_IDS = {
            R.id.tv_cl1, R.id.tv_cl2, R.id.tv_cl3, R.id.tv_cl4,
            R.id.tv_cl5, R.id.tv_cl6, R.id.tv_cl7, R.id.tv_cl8,
            R.id.tv_cl9, R.id.tv_cl10, R.id.tv_cl11, R.id.tv_cl12,
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.activity_main);

        initDBdata();//初始化数据库数据

        findViewById(R.id.sjm_bt1_bz).setOnClickListener(this);
        findViewById(R.id.sjm_bt2_jz).setOnClickListener(this);
        findViewById(R.id.sjm_bt3_hz).setOnClickListener(this);
        findViewById(R.id.tv_pb).setOnClickListener(this);
        findViewById(R.id.sjm_bt5_sz).setOnClickListener(this);

        for (int i = 0; i < CTR_IDS.length; i++) {
            findViewById(CTR_IDS[i]).setOnClickListener(this);
        }

        update();

    }

    void update() {
        ArrayList<Needle> needleList = NeedleCenter.getInstance().getNeedlelist();
        for (Needle needle : needleList) {
            updatestock(needle);
        }
    }

    private void initDBdata() {
        //清空账号
//        MemberCenter.getInstance().clear();
        MemberCenter.getInstance().getMember("admin");
        //目前仅针组需要初始化
        NeedleCenter.getInstance().initZz();//初始化针组

    }

    int _bjnum = 5;//报警数 <= 5

    //更新单个仓位状态
    private void updatestock(Needle needle) {
        if (needle == null) {
            return;
        }
        int i = needle.getPosition() - 1;
        if (i < 0 || i >= CBK_IDS.length) {
            return;
        }

        loadStockbmp(needle);

        ((TextView) findViewById(ZXH_IDS[i])).setText(getString(R.string.sjm_tx_mc) + needle.getName());
        ((TextView) findViewById(CL_IDS[i])).setText(getString(R.string.sjm_tx_cl) + needle.getStock());

        if (needle.getName().length() < 1) {
            findViewById(CBK_IDS[i]).setBackgroundColor(Color.parseColor("#999999"));
            ((TextView) findViewById(ZXH_IDS[i])).setTextColor(Color.parseColor("#454444"));
            ((TextView) findViewById(CL_IDS[i])).setTextColor(Color.parseColor("#454444"));
        } else if (needle.getStock() > _bjnum) {
            findViewById(CBK_IDS[i]).setBackgroundColor(Color.parseColor("#FFFFFF"));
            ((TextView) findViewById(ZXH_IDS[i])).setTextColor(Color.parseColor("#000000"));
            ((TextView) findViewById(CL_IDS[i])).setTextColor(Color.parseColor("#454444"));

        } else {
            //报警 红色
            findViewById(CBK_IDS[i]).setBackgroundColor(Color.parseColor("#E31212"));
            ((TextView) findViewById(ZXH_IDS[i])).setTextColor(Color.parseColor("#FFFFFF"));
            ((TextView) findViewById(CL_IDS[i])).setTextColor(Color.parseColor("#FFFFFF"));
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }


    public static final int REFRESH_UI = 1101;
    public static final int FINISH_JZ = 1102;
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == REFRESH_UI) {
            } else if (msg.what == FINISH_JZ) {
                dismissProgressDialog();
                showShortToast(getString(R.string.ychuzhen));
                updatestock(_selectneedle);
            }
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                onStock(v.getId());
                break;
            case R.id.sjm_bt1_bz:
                onBZ();
                break;
            case R.id.sjm_bt2_jz:
                onJZ();
                break;
            case R.id.sjm_bt3_hz:
                onHZ();
                break;
            case R.id.tv_pb:
                onPB();
                break;
            case R.id.sjm_bt5_sz:
                onSZ();
                break;
        }
    }

    private void onSZ() {
        if (Utils.isFastDoubleClick()) {
            return;
        }
        SystemCenter.getInstance().logintype = 3;
        Intent intent = new Intent(this, LoginActivity.class);
        startActivityForResult(intent, 103);
    }

    private void onStock(int id) {
        _timercount = 0;

        if (Utils.isFastDoubleClick()) {
            return;
        }
        if (_doing == 0) {
            showShortToast(getString(R.string.jzqxdl));
            SystemCenter.getInstance().logintype = 1;
            Intent intent = new Intent(this, LoginActivity.class);
            startActivityForResult(intent, 101);
            return;
        }

        int select = 0;//选中的仓位
        for (int i = 0; i < CTR_IDS.length; i++) {
            if (CTR_IDS[i] == id) {
                select = i;
                break;
            }
        }

        if (select < 0) {
            showShortToast(getString(R.string.weixuanzhong));
            return;
        }

        ArrayList<Needle> needleList = NeedleCenter.getInstance().getNeedlelist();
        _selectneedle = needleList.get(select);
        if (_doing == 1) {
            //借针
            doJz(_selectneedle);
        }
//        else if (_doing == 2) {
//            //还针
//            doHz(_selectneedle);
//        }
    }

    Needle _selectneedle = null;

    private void doHz(Needle needle) {
        if (needle == null) {
            showShortToast(getString(R.string.weixuanzhong));
            return;
        }
        if (needle.getName().length() < 1) {
            showShortToast(getString(R.string.czzwdy));
            return;
        }
        //判断是否有针待还
        Draw_report dr = DrawreportCenter.getInstance().getDraw_report(SystemCenter.getInstance().member.getId(), needle.getId());
        if (dr == null) {
            showShortToast(SystemCenter.getInstance().member.getName() + getString(R.string.wu) + needle.getName() + getString(R.string.dhqqrdlyghzz));
            return;
        }

        SystemCenter.getInstance().needleHz = needle;

        //拍照->验证->管理员输入断针信息
        Intent intent = new Intent(this, HzjcActivity.class);
        startActivityForResult(intent, 200);
    }

    private void doJz(Needle needle) {
        if (needle == null) {
            showShortToast(getString(R.string.weixuanzhong));
            return;
        }

        if (needle.getName().length() < 1) {
            showShortToast(getString(R.string.czzwdy));
            return;
        }

        if (needle.getStock() < 1) {
            showShortToast(needle.getName() + getString(R.string.dclbz));
            return;
        }

        needle.setStock(needle.getStock() - 1);
        NeedleCenter.getInstance().saveNeedle(needle);

        //<---增加借针记录
        //获取当前日期
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date curDate = new Date();
        String strDate = formatter.format(curDate);
        //

        Draw_report draw_report = new Draw_report();
        draw_report.setCreat_time(strDate);
        draw_report.setUpdate_time(strDate);
        draw_report.setNid(needle.getId());
        draw_report.setUid(SystemCenter.getInstance().member.getId());
        draw_report.setNeedle_name(needle.getName());
        draw_report.setMember(SystemCenter.getInstance().member.getName());
        draw_report.setMemberremark(SystemCenter.getInstance().member.getRemark());

        DrawreportCenter.getInstance().insertDraw_report(draw_report);
        //--->

        showProgressDialog(getString(R.string.zzchuzhen));
        new Thread() {
            @Override
            public void run() {
                JtComm.getInstance().sendCommand_chuzhen();
                try {
                    Thread.sleep(1500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                mHandler.sendEmptyMessage(FINISH_JZ);
            }
        }.start();

    }

    //在首页5分钟不操作，则退会屏保
    private void onPB() {
        SystemCenter.getInstance().member = null; //屏保退出登录
        finish();
    }

    private void onHZ() {
        if (Utils.isFastDoubleClick()) {
            return;
        }

        SystemCenter.getInstance().logintype = 2;
        Intent intent = new Intent(this, LoginActivity.class);
        startActivityForResult(intent, 102);
    }

    private void onJZ() {
        if (Utils.isFastDoubleClick()) {
            return;
        }
        SystemCenter.getInstance().logintype = 1;
        Intent intent = new Intent(this, LoginActivity.class);
        startActivityForResult(intent, 101);
    }

    private void onBZ() {
        if (Utils.isFastDoubleClick()) {
            return;
        }

        SystemCenter.getInstance().logintype = 0;
        Intent intent = new Intent(this, LoginActivity.class);
        startActivityForResult(intent, 100);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 666) {
            finish();//重置系统
            return;
        }
        if (resultCode == 777) {
            update();//针组编辑
            return;
        }

        if (resultCode == 999) {
            setResult(999);
            finish();//
            return;
        }

        if (resultCode != RESULT_OK) {
            return;
        }
        if (requestCode == 100) {
            //补针
            _doing = 0;
            Intent intent = new Intent(this, BzglActivity.class);
            startActivityForResult(intent, 1000);
        } else if (requestCode == 1000) {
            update();
        } else if (requestCode == 103) {
            //设置
            _doing = 0;
            Intent intent = new Intent(this, StszActivity.class);
            startActivityForResult(intent, 1030);
        } else if (requestCode == 101) {
            //借针
            _doing = 1;
//            Intent intent = new Intent(this, StszActivity.class);
//            startActivityForResult(intent, 1010);
        } else if (requestCode == 102) {
            //还针
//            _doing = 2;
            onHz2(); //登录成功后进入员工的可还针列表
        }
    }

    //进入可还针的列表
    private void onHz2() {
        ArrayList<Draw_report> list = DrawreportCenter.getInstance().getDraw_reportlistbyuid(SystemCenter.getInstance().member.getId());
        if (list.size() < 1) {
            showShortToast(getString(R.string.wwhzdjl));
            return;
        }
        DrawreportCenter.getInstance().drlist = list;

        Intent intent = new Intent(this, HzActivity.class);
        startActivityForResult(intent, 300);
    }

    int _doing = 0;// 0-不能操作 1-正在借针 2-正在还针

    void loadStockbmp(Needle needle) {
        if (needle == null) {
            return;
        }
        String imagePath = "" + needle.getImg();
        // 使用BitmapFactory解码图片文件
        Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
        if (bitmap == null) {
            return;
        }

        int i = needle.getPosition() - 1;
        if (i < 0 || i >= CBK_IDS.length) {
            return;
        }
        // 将Bitmap设置到ImageView中
        ImageView imageView = findViewById(STOCK_IDS[i]);
        imageView.setImageBitmap(bitmap);


    }

    @Override
    public void initView() {

    }

    @Override
    public void initData() {

    }

    @Override
    public void initEvent() {

    }

    @Override
    protected void onResume() {
        super.onResume();
        _timercount = 0;
        TimeRefresher.getInstance().addTimeRefreshListener(TAG, 1000, this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        TimeRefresher.getInstance().removeTimeRefreshListener(TAG);
    }

    @Override
    public void onTimerStart() {

    }

    private int _timercount = 0;

    @Override
    public void onTimerRefresh() {
        _timercount++;
        if (_timercount > 60) {
            finish();
        }
    }

    @Override
    public void onTimerStop() {

    }
    // 假设你已经有了图片文件的路径


}
/*
自动拍照保存文件，并使用bimap
1. TextureView 的 layout_width设为1dp 不影响生成的图片
2. 手动调用 createCameraPreviewSession(); 会重新生成图片 (初始化的时候存了1张照片)
3. pad摄像头800w像素，3264x2448
   改变存图的尺寸为 352x288   -- 54KB

**             imageReader = ImageReader.newInstance(_imagw, _imagh, IMAGE_FORMAT, 2); --不乱改尺寸就cameraDevice就不会出错关闭
SystemCenter.getInstance().hzBitmap -- 保存原始的位图
图片文件保存缩小尺寸
 */
